#!/usr/bin/env python
#
# Demo file for simple database interactions and JSON usage.

import cgi
import datetime
import urllib
import simplejson as json
import wsgiref.handlers

from google.appengine.ext import db
from google.appengine.api import users
from google.appengine.ext import webapp
from google.appengine.ext.webapp import util

# We only need one database.  If you want multiple, 
# you don't always have to reference the same string (Ancestor value).
MYDATABASE = 'HypeDatabase'


class MainHandler(webapp.RequestHandler):
  """Page handler for '/' location."""
  def get(self):
    self.response.out.write('Hello Team Hype!')
    
    
class EventInfo(db.Model):
  """Defines the columns in our database."""
  event = db.StringProperty(multiline=False)
  name = db.StringProperty(multiline=False)
  date_time = db.DateTimeProperty()
  location = db.GeoPtProperty()	
  rating = db.IntegerProperty()
  
  
def eventtinfo_key(eventinfo_name=None):
  """Constructs a datastore key for a UserInfo entity with userinfo_name."""
  return db.Key.from_path('Guestbook', eventinfo_name or 'default_guestbook')
    
    
class GetDataHandler(webapp.RequestHandler):
  """Page handler for '/getdata' location."""
  def get(self):
    event_request = self.request.get('event')
    
    # Verify a name was passed:
    if not name_request:
      self.response.out.write('Need to request something.')
      return
      
    # Get results from database:
    rows = db.GqlQuery('SELECT * FROM EventInfo WHERE ANCESTOR IS :ancestor AND name = :event', 
                       ancestor=eventinfo_key(MYDATABASE), event=event_request)
                       
    # Verify results exist, if not, send a fake empty json object.
    if not rows.count():
      self.response.out.write('{"data": ""}')
      return
    
    # Collect items in a list
    items = []  # Empty list
    for eventinfo in rows:
      items.append({userinfo.event: userinfo.info})  # Append each user/info pair
      
    # label list as "data" and create a json object
    jsonobject = json.dumps({'data': items})
    self.response.out.write(jsonobject)  # send (print) the json object.
    
  
class PutDataHandler(webapp.RequestHandler):
  """Page handler for '/putdata' location."""
  def get(self):
    event = self.request.get('event')    
    name = self.request.get('name')    
    date_time = self.request.get('date_time')
    location = self.request.get('location')	
    rating = self.request.get('rating')
    if not name or not event:
      self.response.out.write('need event and name.')
      return
    # Create a EventInfo object, add the keys, then put it into the database.
    eventinfo = EventInfo(parent=eventinfo_key(MYDATABASE))
    eventinfo.event = event
    eventinfo.name = name
    eventinfo.date_time = date_time
    eventinfo.location = location
    eventinfo.rating = rating
    eventinfo.put()
    self.response.out.write('Done.')


def main():
  application = webapp.WSGIApplication([('/', MainHandler),
                                        ('/getdata', GetDataHandler),  # this is where the classes are linked to url locations
                                        ('/putdata', PutDataHandler)],
                                       debug=True)
  util.run_wsgi_app(application)


if __name__ == '__main__':
  main()
